
let depId = 0
export class Dep {
    constructor() {
        this.id = depId++
        this.exp = ''
        this.subs = []
    }
    addSub(sub) {
        this.subs.push(sub)
    }
    removeSub(sub) {
        if (this.subs.length) {
            const index = this.subs.indexOf(sub)
            if (index > -1) {
                return this.subs.splice(index, 1)
            }
        }
    }
    depend() {
        if (Dep.target) {
            Dep.target.addDep(this)
        }
    }
    notify() {
        const subs = this.subs.slice()
        subs.sort((a, b) => a.id - b.id)
        for (let i = 0, l = subs.length; i < l; i++) {
            subs[i].update()
        }
    }
}

/**
 * 观察者压栈
 */
const targetStack = []
Dep.target = null

export function pushTarget(target) {
    targetStack.push(target)
    Dep.target = target
}

export function popTarget() {
    targetStack.pop()
    Dep.target = targetStack[targetStack.length - 1]
}

